package A3GCPackage;

import java.util.Collection;
import java.util.Date;

import org.jgroups.Address;
import org.jgroups.JChannel;
import org.jgroups.blocks.ReplicatedHashMap;

public class NodeData 
{
	protected ReplicatedHashMap< String, SingleNodeData > nodeMap;
	
	public NodeData( JChannel channel )
	{
		nodeMap = new ReplicatedHashMap<String, SingleNodeData>(channel);
	}
	
	public Collection<SingleNodeData> getNodes()
	{
		return nodeMap.values();
	}
	
	public void setNodeActivity( String name, boolean active, String groupName, Address address )
	{
		SingleNodeData snd = nodeMap.get( name );
		
		if ( snd == null )
		{
			// create a new node for the map;
			snd = new SingleNodeData();
			snd.name      = name;
			snd.active    = active;
			snd.decay     = 0;
			snd.group     = groupName;
			snd.timestamp = new Date( System.currentTimeMillis() );
			snd.address   = address;
		}
		else
		{
			snd.active    = active;
			snd.timestamp = new Date( System.currentTimeMillis() );
			snd.group     = groupName;
			snd.address   = address;
			
		}
		
		// Tom (2012-05-22): does replicated hash map accept the same object back in? 
		// and is this enough to get the others updated.
		System.out.println("Temporary Debug: map is being updated: " + name );
		System.out.println("\t\tgroupName = " + groupName + "\t address = " + address );
		nodeMap.put(name, snd);
	}
	
	public void addNodeIfNotExistent( String name, String groupName, Address address )
	{
		SingleNodeData snd = nodeMap.get(name);
		
		if ( snd == null )
		{
			snd = new SingleNodeData();
			snd.name      = name;
			snd.active    = false;
			snd.decay     = 0;
			snd.group     = groupName;
			snd.timestamp = new Date( System.currentTimeMillis() );
			snd.address   = address;
			
			System.out.println("addNodeIfNotExistent: adding a node with name <" + name + "> and group <" + groupName + ">" );
			nodeMap.put( name, snd );
		}
	}
	
	public void deleteNodeIfSameGroup( String name, String groupName )
	{
		SingleNodeData snd = nodeMap.get( name );
		
		if ( snd != null )
		{
			if ( snd.group.compareTo( groupName ) == 0 )
			{
				nodeMap.remove( name );
			}
		}
	}
}
